# coding:utf-8
"""
给没有套餐的工程商写入一条初始套餐记录

"""
import os
import time
import json
from datetime import date, timedelta
import set_env_path     # 请勿删除

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import text

Base = declarative_base()

engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
Session = sessionmaker(bind=engine)
session = Session()


def generate_pack():
    """
    created by chenhj at 2017/9/13

    """
    select_no_pack_user_id_sql = """
        select id, area_id from user
         where type=100 and deleted_at=0 and is_virt=0 and id 
          not in (select uid from pack where deleted_at=0);
    """

    insert_pack_sql = text("""
        insert into pack(
          uid, area_id, call_point, sms_point, accum_call_point, accum_sms_point,
           end_date, created_at
        ) values (:uid, :area_id, :call_point, :sms_point, :accum_call_point,
                  :accum_sms_point, :end_date, :created_at )
    """)

    today = date.today()
    result = session.execute(select_no_pack_user_id_sql).fetchall()
    for each in result:
        print(each.id)
        session.execute(
            insert_pack_sql,
            {
                'uid': each.id,
                'area_id': json.dumps([each.area_id]),
                'call_point': 3,
                'sms_point': 115,
                'accum_call_point': 3,
                'accum_sms_point': 115,
                'end_date': today + timedelta(days=30),
                'created_at': int(time.time())
            }
        )
    session.commit()
    session.close()


if __name__ == '__main__':
    generate_pack()
